"use client"

import * as React from "react"
import { Shell } from "@/components/shell"
import { InformationButton } from "@/components/information/information-button"
import { VendorPoolVirtualTable } from "@/lib/vendor-pool/table/vendor-pool-virtual-table"
import { Skeleton } from "@/components/ui/skeleton"
import type { VendorPoolItem } from "@/lib/vendor-pool/table/vendor-pool-table-columns"
import { toast } from "sonner"

export default function VendorPoolPage() {
  const [data, setData] = React.useState<VendorPoolItem[]>([])
  const [isLoading, setIsLoading] = React.useState(true)

  // 전체 데이터 로드
  const loadData = React.useCallback(async () => {
    setIsLoading(true)
    try {
      const response = await fetch('/api/vendor-pool/all')
      if (!response.ok) {
        throw new Error('Failed to fetch data')
      }
      const result = await response.json()
      setData(result)
    } catch (error) {
      console.error('Failed to load vendor pool data:', error)
      toast.error('데이터를 불러오는데 실패했습니다.')
    } finally {
      setIsLoading(false)
    }
  }, [])

  // 초기 로드
  React.useEffect(() => {
    loadData()
  }, []) // ✅ 빈 배열로 변경 - 마운트시에만 실행

  // 새로고침 핸들러 - useRef를 사용하여 안정적인 참조 유지
  const loadDataRef = React.useRef(loadData)
  React.useEffect(() => {
    loadDataRef.current = loadData
  }, [loadData])

  const handleRefresh = React.useCallback(() => {
    loadDataRef.current()
  }, []) // ✅ 빈 배열로 변경 - 함수 재생성 방지

  return (
    <Shell variant="fullscreen" className="gap-2 h-[calc(100vh-150px)]">
      <div className="flex items-center justify-between space-y-2">
        <div className="flex items-center justify-between space-y-2">
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-2xl font-bold tracking-tight">
                Vendor Pool
              </h2>
              <InformationButton pagePath="evcp/vendor-pool" />
            </div>
          </div>
        </div>
      </div>

      {isLoading ? (
        <div className="space-y-4 flex-1 flex flex-col">
          <Skeleton className="h-10 w-full" />
          <Skeleton className="h-full w-full flex-1" />
        </div>
      ) : (
        <VendorPoolVirtualTable data={data} onRefresh={handleRefresh} />
      )}
    </Shell>
  )
}
